package com.tbabs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbabs.common.R;
import com.tbabs.entity.User;
import com.tbabs.service.UserService;
import com.tbabs.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        // 获取手机号
        String phone = user.getPhone();
        if (StringUtils.isEmpty(phone)) {
            // 手机号为null,返回提示
            return R.error("手机号获取失败！");
        }

        // 生成随机4为验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        // 调用阿里云短信服务发送短信
        // 这里由于没有阿里云短信服务，所以这里只是写一个模板，
        // 通过日志记录验证码
//        SMSUtils.sendMessage("短信签名","模板code", phone, code);
        log.info("code={}",code);

        // 将生成的验证码保存在redis缓存中
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        return R.success(code);
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<Object, Object> map, HttpSession session){
        // 获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        // 获取redis缓存中的验证码
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);
        // 验证码比对
        if (sessionCode != null && sessionCode.equals(code)) {
            // 判断当前手机号是否已经注册过，未注册则自动注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            // 登录成功即可删除缓存中的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败，验证码不符！");
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功！");
    }
}
